#include <unistd.h>
#include <linux/ip.h>
#include <string.h>
#include <time.h>

#include "opendpi_db_task.h"
#include "sql.h"
#include "protocols.h"
#include "log.h"
#include "msg.h"

extern char *prot_long_str[]; 
#define IPOQUE_MAX_SUPPORTED_PROTOCOLS 118 /* TODO: Because opendpi is a beta version now, so it should be changed later. */
extern unsigned long protocol_counter[];
extern unsigned long protocol_counter_bytes[];
#define TIME_INTERVAL 5
#define TIME_TABLE_INTERVAL 60
//#define TIME_TABLE_INTERVAL 3600
static unsigned long time1 = 0;
static unsigned long time2 = 0;
static unsigned long table_time1 = 0; 
static unsigned long table_time2 = 0; 
static char table_name[128] = {'\0'};

static int table_id = 0;
static unsigned int table_protocol_id = 0;

int opendpi_db_ops(struct msg *msg)
{
	log_info("begin opendpi_db_ops.");

	return 0;
}

void *opendpi_db_loop(void *conf)
{
	log_info("begin opendpi_db_loop.");

	sql_init();

	int res;
	res = sql_query("create table opendpiTableInfo(id int, tableName char(128))");
	if (res) {
		log_print("sql_query error: %d, %s\n", sql_errorno(), sql_error());
	}

	while (1) {
		table_time2 = time(NULL);
		if (table_time2 >= table_time1 + TIME_TABLE_INTERVAL) {
			char cmd[1024] = {'\0'};

			sprintf(table_name, "opendpiInfo%lu", table_time2);
			sprintf(cmd, "create table %s(id int, protocolName char(64), protocolCounter bigint, protocolBytes bigint)", table_name);
			res = sql_query(cmd);
			if (res) {
				log_print("sql_query error: %d, %s\n", sql_errorno(), sql_error());
			}
	
			sprintf(cmd, "insert into opendpiTableInfo values(%d, '%s')", table_id, table_name);
			table_id++;
			res = sql_query(cmd);
			if (res) {
				log_print("sql_query error: %d, %s\n", sql_errorno(), sql_error());
			}
	
			table_time1 = table_time2;
		}

		time2 = time(NULL);	
		if (time2 >= time1 + TIME_INTERVAL) {
			time1 = time2;


			char cmd[1024] = {'\0'};
			unsigned int i;
			int is_begin = 0;


/*

		        char str[2000];
                        int str_str=0;
			int num=0;
                        str_str=sprintf(str,"%s","sh rrd/rrd_insert.sh ");
                        for(num=0;num<IPOQUE_MAX_SUPPORTED_PROTOCOLS;num++)
			{
				str_str+=sprintf(str+str_str,"%lu",protocol_counter[num]);
				str_str+=sprintf(str+str_str,"%s"," ");
			}
			system(str);
*/

			for(i = 0; i < IPOQUE_MAX_SUPPORTED_PROTOCOLS; i++) {

			if(protocol_counter[i] > 0) {
					is_begin = 1;
					sprintf(cmd,"insert into %s values(%d,'%s',%lu,%lu)", table_name,
							table_protocol_id,prot_long_str[i],protocol_counter[i],
							protocol_counter_bytes[i]);
					res = sql_query(cmd);
					if (res) {
						log_print("sql_query error: %d, %s\n", sql_errorno(), sql_error());
					}

				}
	
			}

			if (is_begin == 1) {
				table_protocol_id++;
			}
		}

	}
}
